package com.graduation.project.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.ftp.Ftp;
import com.jcraft.jsch.IO;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

public class FtpUtil {

    // ftp服务器地址
    private static final String FTP_ADDRESS = "106.13.210.87";
    // 端口号
    private static final int FTP_PORT = 21;
    // 用户名
    private static final String FTP_USERNAME = "root";
    // 密码
    private static final String FTP_PASSWORD = "440828zyf@";
    // 附件路径
    private static final String FTP_BASE_PATH = "/www/wwwroot/zyf-file/";

    public static void upload() {
        Ftp ftp = new Ftp(FTP_ADDRESS, FTP_PORT);
        ftp.upload("/root/test", FileUtil.file("C:\\Users\\admin\\Desktop\\1.jpg"));
    }

    public static String uploadFile(MultipartFile file, String userCode) {
        // 获取上传的文件名
        String fileName = file.getOriginalFilename();
        // 截取后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 使用UUID拼接出新的文件名
        fileName = IdUtil.simpleUUID() + suffix;

        FTPClient ftpClient = new FTPClient();
        try {
            // 获取上传文件的文件流
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();

            ftpClient.connect(FTP_ADDRESS, FTP_PORT); // 连接FTP服务器
            ftpClient.login(FTP_USERNAME, FTP_PASSWORD); // 登录
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                return "";
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.makeDirectory(FTP_BASE_PATH + userCode);
            ftpClient.changeWorkingDirectory(FTP_BASE_PATH + userCode);
            ftpClient.storeFile(fileName, fileInputStream);
            fileInputStream.close();
            ftpClient.logout();
        }catch (IOException e) {
            e.printStackTrace();
            return "";
        }finally {
            try {
                ftpClient.disconnect();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

}
